<template>
  <li :class="[menu.isGroup ? 'va-menu-group' : 'va-menu-item']">
    <div class="va-menu-title" :class="{'has-children': hasChildren, expanded: menu.expanded, active: menu.active}" @click="toggleExpansion">
      <template v-if="menu.html">
        <div v-html="menu.html"></div>
      </template>
      <template v-else>
        <span>{{menu.label}}</span>
      </template>
    </div>
    <template v-if="hasChildren">
      <collapse-transition>
        <va-menu v-show="menu.expanded" :menus="menu.children" :is-child="true" :level="level + 1" @menu-active="onMenuActive"></va-menu>
      </collapse-transition>
    </template>
  </li>
</template>

<script>
  import VaMenu from './VaMenu.vue'
  import CollapseTransition from '../libs/transitions/collapse-transtion'
  export default {
    components: {VaMenu, CollapseTransition},
    props: {
      menu: {
        required: true
      },
      level: {
        type: Number,
        required: true
      }
    },
    data () {
      return {}
    },
    methods: {
      toggleExpansion () {
        if (this.hasChildren) {
          this.$set(this.menu, 'expanded', !this.menu.expanded)
        } else if (this.menu.link) {
          this.$router.push(this.menu.link)
        }
      },
      onMenuActive () {
        this.$set(this.menu, 'active', true)
        this.$set(this.menu, 'expanded', true)
      }
    },
    computed: {
      hasChildren () {
        return this.menu.children && this.menu.children.length > 0
      }
    },
    watch: {
      'menu.active' () {
        if (this.menu.active) {
          this.$emit('menu-active')
        }
      }
    }
  }
</script>
